package socket

import (
	"chart.zozoo.net/app/service/userService"
	"chart.zozoo.net/app/socket/connManage"
	"chart.zozoo.net/app/socket/readHandle"
	"chart.zozoo.net/app/utils/rsp"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
)

var myUpgrade = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {

		return true // 或者根据需要检查 Origin
	},
}

// Handle SocketHandle 处理socket
func Handle(c *gin.Context) {
	uuid := c.GetString("uuid")

	//获取用户信息
	userInfo, err := userService.InfoByUuid(uuid)
	if err != nil {
		rsp.JsonErr(c, rsp.SetMsg(err.Error()))
		return
	}

	//获取websocket连接
	conn, err := myUpgrade.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		rsp.JsonErr(c, rsp.SetMsg(err.Error()))
		return
	}

	//将连接保存进全局变量中
	connManage.AddConn(userInfo, conn)
	go readHandle.ReadHandle(conn)
}
